import os
import parsel
import requests
# 漫画网址
url = 'https://cn.baozimhcn.com/comic/silingfashiwojishitianzai-mantudezhuyuanzhuheiniaoshe'
# 请求头
headers = {
    'referer': 'https://cn.baozimhcn.com/classify',
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.67',
}
# 向漫画网址发送请求
resp = requests.get(url, headers=headers)
# 解析数据，处理网页源代码
selector = parsel.Selector(resp.text)
# 通过Selector对象来选择源代码中的特定元素
span_list = selector.css('.comics-chapters__item span::text').getall()
# 获取章节链接
chapter_links = selector.css('#chapters_other_list > div.comics-chapters a::attr(href)').getall()
chapter_links1 = selector.css('#chapter-items > div.comics-chapters a::attr(href)').getall()
# 合并章节链接列表
all_chapter_links = chapter_links1 + chapter_links
# 使用Session对象来跟踪重定向历史
session = requests.Session()
# 通过for循环遍历 并且进行了排序  从第一话开始
for link in all_chapter_links:
    # 构造完整的章节URL
    index_url = 'https://cn.baozimhcn.com' + link
    # 发送请求获取章节内容
    resp = session.get(index_url, headers=headers, allow_redirects=True)
    # 解析返回的页面内容
    selector = parsel.Selector(resp.text)
    image_links = selector.css('img::attr(src)').getall()
    chapter_title = selector.css('title::text').get().strip()
    # 创建章节文件夹
    file_name = f'{chapter_title.replace("/", "_").replace(" ", "_")}\\'  # 替换特殊字符
    if not os.path.exists(file_name):
        os.mkdir(file_name)
    # 下载图片
    for i, img_url in enumerate(image_links):
        # 完整的图片URL
        full_img_url = 'https:' + img_url if img_url and not img_url.startswith('http') else img_url
        if full_img_url:
            img_resp = session.get(full_img_url, headers=headers)
            if img_resp.status_code == 200:
                # 保存图片到本地
                image_path = os.path.join(file_name, f"{i + 1}.jpg")
                with open(image_path, 'wb') as file:
                    file.write(img_resp.content)
                print(f"图片已保存为：{image_path}")
            else:
                print(f"下载图片失败，状态码：{img_resp.status_code}")